/**
 * 产品分类列表
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */

var treeGrid = null, tableId = 'zmn-table';
layui.define(['index', 'form', 'table', 'laypage', 'layedit',"treeGrid"], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    treeGrid = layui.treeGrid;
    var data = {parentId: json.vo.parentId==0?1:json.vo.parentId,orgId: json.vo.orgId};//查询条件
    treeGrid.render({
        id: tableId
        , elem: '#' + tableId
        , url: '/system/organ/depamentTree.action'
        , where: data
        , cellMinWidth: 100
        , idField: 'deptId'//必須字段
        , treeId: 'deptId'//树形id字段名称
        , treeUpId: 'parentId'//树形父id字段名称
        , treeShowName: 'deptName'//以树形式显示的字段
        , heightRemove: [".dHead", 10]//不计算的高度,表格设定的是固定高度，此项不生效
        , height: '100%'
        , isFilter: false
        , iconOpen: true//是否显示图标【默认显示】
        , isOpenDefault: false//节点默认是展开还是折叠【默认展开】
        , loading: true
        , method: 'post'
        , isPage: false
        , toolbar: "#zmn-table-tool"
        , cols: [[
            {type: 'checkbox',field: 'orgId', width: 50, unresize: true},
            {field: 'sort', title: '排序', width: 80, align: 'center', edit: 'text', unresize: true, sort: false,event:"editClick"},
            {field: 'deptId', title: '部门ID', width: 80, align: 'center', unresize: true, sort: false,templet:(d)=>{
                    if (d.orgId) {
                        return d.orgId;
                    } else {
                        return "--"
                    }
                }},
            {field: 'deptName',  title: '部门名称', width: 350, sort: true, unresize: true},
            {field: 'keyStaffs', title: '部门负责人', width: 80, align: 'center', unresize: true, sort: false, templet:(d)=>{
                    if (d.keyStaffs) {
                        return d.keyStaffs;
                    } else {
                        return "--";
                    }
                }},
            {
                    field: 'status', title: '状态', width: 80, align: 'center', unresize: true, templet: function (d) {
                        return zmnEnum.STATUS[d.status];
                    }
                },
            {field: 'updater', title: '最近修改人/时间', width: 300, align: 'center', unresize: true,templet:function (row) {
                return row.updater+"/"+zmnUtil.createTime(row.updateTime);
                    
                }},
            {
                 title: '操作', align: 'center'
                , templet: function (row) {
                    var html = '';
                    var nextDepartment = '<a style="color: #00a0e9" lay-text="下级部门" lay-href="/system/organ/departments.action?parentId='+row.deptId+'&orgId='+row.orgId+'&flag=2">下级部门</a>&nbsp;&nbsp;&nbsp;&nbsp;';
                    var update = '<a  style="color: #00a0e9"  lay-text="修改部门" lay-href="/system/organ/deptDetail.action?orgId='+row.orgId+'&deptId='+row.deptId+'">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;';
                    return nextDepartment + update;
                }
            }
        ]]
        , parseData: function (res) {//数据加载后回调
            return res;
        }
    });
    //重写选中事件，规避子节点没选全选中父节点的bug
    treeGrid.getClass(tableId).eventsinit = function(){
        //字符常量

        MOD_NAME = 'treeGrid', ELEM = '.layui-table', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled', NONE = 'layui-none'
            ,ELEM_VIEW = 'layui-table-view', ELEM_HEADER = '.layui-table-header', ELEM_BODY = '.layui-table-body', ELEM_MAIN = '.layui-table-main', ELEM_FIXED = '.layui-table-fixed', ELEM_FIXL = '.layui-table-fixed-l', ELEM_FIXR = '.layui-table-fixed-r', ELEM_TOOL = '.layui-table-tool', ELEM_PAGE = '.layui-table-page', ELEM_SORT = '.layui-table-sort', ELEM_EDIT = 'layui-table-edit', ELEM_HOVER = 'layui-table-hover'
            ,TABLE_RADIO_ID='table_radio_',TABLE_CHECKBOX_ID='layTableCheckbox'
            ,ELEM_FILTER='.layui-table-filter'
            ,TREE_ID='treeId',TREE_UPID='treeUpId',TREE_SHOW_NAME='treeShowName',TREE_KEY_MAP='tree_key_map'
        var that = this
            ,options = that.config
            ,ELEM_CELL = '.layui-table-cell'
            ,filter = options.elem.attr('lay-filter');
        //行内过滤
        that.layFilter.on('keyup',"[name^='filter_']",function () {
            that.page=1;
            that.pullData(that.page, that.loading());
        });
        //行事件
        that.layBody.on('mouseenter','tr',function(){
            var othis = $(this)
                ,index = othis.index();
            that.layBody.find('tr:eq('+ index +')').addClass(ELEM_HOVER)
        })
        that.layBody.on('mouseleave','tr', function(){
            var othis = $(this)
                ,index = othis.index();
            that.layBody.find('tr:eq('+ index +')').removeClass(ELEM_HOVER)
        });
        //单元格事件
        that.layBody.on('click','td div.layui-table-cell p',function(){
            var othis = $(this).parent().parent()
                ,field = othis.data('field')
                ,editType = othis.data('edit')
                ,index = othis.parents('tr').eq(0).data('index')
                ,data = treeGrid.getDataList(that.key)[index]
                ,elemCell = othis.children(ELEM_CELL);
            var  options = that.config;
            layer.close(that.tipsIndex);
            if(othis.data('off')) return;

            //显示编辑表单
            if(editType&&options.editModel=="click"){
                that.renderTdEdit(index,field);
                return;
            }

            //如果出现省略，则可查看更多
            var c=that.getCols(field);

            if(!treeGrid.config.initWidth[c["type"]]){
                if(elemCell.find('.layui-form-switch,.layui-form-checkbox')[0]) return; //限制不出现更多（暂时）
                if(Math.round(elemCell.prop('scrollWidth')) > Math.round(elemCell.outerWidth())){
                    that.tipsIndex = layer.tips([
                        '<div class="layui-table-tips-main" style="margin-top: -'+ (elemCell.height() + 16) +'px;'+ function(){
                            if(options.size === 'sm'){
                                return 'padding: 4px 15px; font-size: 12px;';
                            }
                            if(options.size === 'lg'){
                                return 'padding: 14px 15px;';
                            }
                            return '';
                        }() +'">'
                        ,elemCell.html()
                        ,'</div>'
                        ,'<i class="layui-icon layui-table-tips-c">&#x1006;</i>'
                    ].join(''), elemCell[0], {
                        tips: [3, '']
                        ,time: -1
                        ,anim: -1
                        ,maxWidth: (device.ios || device.android) ? 300 : 600
                        ,isOutAnim: false
                        ,skin: 'layui-table-tips'
                        ,success: function(layero, index){
                            layero.find('.layui-table-tips-c').on('click', function(){
                                layer.close(index);
                            });
                        }
                    });
                }
            }
        });
        //单元格事件
        that.layBody.on('dblclick','td div.layui-table-cell p',function(){
            var othis = $(this).parent().parent()
                ,field = othis.data('field')
                ,editType = othis.data('edit')
                ,index = othis.parents('tr').eq(0).data('index')
                ,data = treeGrid.getDataList(that.key)[index]
                ,elemCell = othis.children(ELEM_CELL);
            var  options = that.config;
            layer.close(that.tipsIndex);
            if(othis.data('off')) return;
            //显示编辑表单
            if(editType&&options.editModel=="dblclick"){
                that.renderTdEdit(index,field);
                return;
            }
        });
        that.layBody.on('change','.'+ELEM_EDIT, function(){
            var othis = $(this)
                ,value = this.value
                ,field = othis.parent().data('field')
                ,index = othis.parents('tr').eq(0).data('index')
                ,data = treeGrid.getDataList(that.key)[index];
            data[field] = value; //更新缓存中的值
            layui.event.call(this, MOD_NAME, 'edit('+ filter +')', {
                value: value
                ,data: data
                ,field: field
            });
        });
        that.layBody.on('blur','.'+ELEM_EDIT, function(){//单元格失去焦点
            var templet
                ,othis = $(this)
                ,field = othis.parent().data('field')
                ,index = othis.parents('tr').eq(0).data('index')
                ,editType = othis.parent().data('edit')
                ,data = treeGrid.getDataList(that.key)[index];
            var  options = that.config;
            that.eachCols(function(i, item){
                if(item.field == field && item.templet){
                    templet = item.templet;
                }
            });
            var value="";
            if(editType === 'select') { //选择框
                var rowsField=dl.ui.table.drop.findFieldObj(options.cols[0],field);
                if(rowsField&&rowsField['drop']){
                    var o=dl.cache.code.get(rowsField.drop);
                    value=dl.ui.table.drop.findDropLable(rowsField.drop,this.value);
                }
                othis.parent().find(ELEM_CELL+' p').html(
                    templet ? laytpl($(templet).html() || value).render(data) : value
                );
            } else {//输入框
                othis.parent().find(ELEM_CELL+' p').html(
                    templet ? laytpl($(templet).html() || this.value).render(data) : this.value
                );
            }
            othis.parent().data('content', this.value);
            othis.remove();
        });
        //树形节点点击事件（隐藏展开下级节点）
        that.elem.on('click','i.layui-tree-head', function(){
            var othis = $(this)
                ,index = othis.parents('tr').eq(0).data('index')
                ,options=that.config
                ,datas=treeGrid.getDataList(that.key);//数据
            var o=datas[index];
            that.treeNodeOpen(o,!o[treeGrid.config.cols.isOpen]);
            that.resize();
        });
        //复选框选择
        that.elem.on('click', 'input[name="' + TABLE_CHECKBOX_ID + '"]+', function() {
            var checkbox = $(this).prev(),
                childs = that.layBody.find('input[name="' + TABLE_CHECKBOX_ID + '"]'),
                index = checkbox.parents('tr').eq(0).data('index'),
                checked = checkbox[0].checked,
                obj = treeGrid.getDataList(that.config.id)[index],
                isAll = checkbox.attr('lay-filter') === 'layTableAllChoose';
            //全选
            if (isAll) {
                var list = treeGrid.getDataList(that.key);
                list.forEach(function(temo) {
                    if (!temo[treeGrid.config.cols.cheDisabled]) { //可以选择的才设置
                        that.setCheckData(temo[treeGrid.config.indexName], checked);
                    }
                });
            } else {
                that.setCheckData(index, checked);
                if (options.isTree) {
                    //处理下级
                    var sonList = that.treeFindSonData(obj);
                    sonList.forEach(function(temo) {
                        if (!temo[treeGrid.config.cols.cheDisabled]) { //可以选择的才设置
                            that.setCheckData(temo[treeGrid.config.indexName], checked);
                        }
                    });

                    //处理上级
                    var temf = function(o) {
                        if (o == null) return;
                        if (o && o.children.length > 0) {
                            var temis = true;
                            o.children.forEach(function(temo) {
                                if (!temo[treeGrid.config.cols.isCheckName]) {
                                    temis = false;
                                    o[treeGrid.config.cols.isCheckName]=false
                                }
                            });
                            if (temis) {
                                that.setCheckData(o[treeGrid.config.indexName], checked);
                            }

                            var temuo = that.treeFindUpData(o);
                            if (temuo) {
                                temf(temuo);
                            }
                        }
                    }
                    var uo = that.treeFindUpData(obj);
                    temf(uo);
                }
            }
            that.syncCheckAll();
            layui.event.call(this, MOD_NAME, 'checkbox(' + filter + ')', {
                checked: checked,
                data: treeGrid.getDataList(that.key) ? (obj || {}) : {},
                type: isAll ? 'all' : 'one'
            });
            typeof options.onCheck === 'function' && options.onCheck(obj, checked, isAll);
        });

        //单选框选择
        that.elem.on('click','input[name="'+TABLE_RADIO_ID+'"]+', function(){
            var checkbox = $(this).prev()
                ,index = checkbox.parents('tr').eq(0).data('index')
                ,obj=treeGrid.getDataList(that.config.id)[index];
            typeof options.onRadio === 'function' && options.onRadio(obj);
        });

        //工具条操作事件
        that.layBody.on('click', '*[lay-event]',function(){
            var othis = $(this)
                ,index = othis.parents('tr').eq(0).data('index')
                ,tr = that.layBody.find('tr[data-index="'+ index +'"]')
                ,ELEM_CLICK = 'layui-table-click'
                ,list = treeGrid.getDataList(that.key)
                ,data = treeGrid.getDataList(that.key)[index];
            layui.event.call(this, MOD_NAME, 'tool('+ filter +')', {
                data: data//table.clearCacheKey(data)
                ,event: othis.attr('lay-event')
                ,tr: tr
                ,del: function(){
                    treeGrid.delRow(options.id,data);
                }
                ,update: function(fields){
                    fields = fields || {};
                    layui.each(fields, function(key, value){
                        if(key in data){
                            var templet, td = tr.children('td[data-field="'+ key +'"]');
                            data[key] = value;
                            that.eachCols(function(i, item2){
                                if(item2.field == key && item2.templet){
                                    templet = item2.templet;
                                }
                            });
                            td.children(ELEM_CELL).html(
                                templet ? laytpl($(templet).html() || value).render(data) : value
                            );
                            td.data('content', value);
                        }
                    });
                }
            });
            tr.addClass(ELEM_CLICK).siblings('tr').removeClass(ELEM_CLICK);
        });
    }


    let clickedData = {};
    treeGrid.on('tool('+tableId+')',function (obj) {
        if(obj.event=='editClick'){
            clickedData = {"id":obj.data.deptId,"orgSort":obj.data.sort};
        }
    });


    //索引编辑事件
    $(document).delegate('.layui-table-edit','blur keydown', function (e) {
        if((e.keyCode && e.keyCode==13)||e.type=='focusout'){
            let updateVal = $(this).val();
            if(clickedData.orgSort!=updateVal){
                clickedData.orgSort = updateVal;
                zmnPage.ajaxSimple("/mc/dept/updateSort.action",{"id" : clickedData.id, "sort" : updateVal}, 0);
            }
        }

    });
    $(document).on('click', '.changeStatus ', function () {
        let obj= {"event":$(this).attr("lay-event")};
        let checkStatus = treeGrid.checkStatus(tableId)
            , data = checkStatus.data;
        let orgIds = "";
        layui.each(data, function (i, item) {
            orgIds += item.deptId+",";
        });
        if( orgIds == ""){
            return layer.alert("请选择至少一条数据！");
        }
        zmnPage.layStartStop(obj, "/mc/dept/updateStatus.action", orgIds.substring(0,orgIds.length-1));
    });


    //对外暴露的接口
    exports('art_organ_department_list', {});
});
